﻿using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Receive
{
    class Program
    {
        /// <summary>
        /// 接收方
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            var factory = new ConnectionFactory();
            factory.HostName = "localhost";
            factory.UserName = "yy";
            factory.Password = "hello!";

            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    //channel.QueueDeclare("hello", false, false, false, null);
                    //var consumer = new QueueingBasicConsumer(channel);
                    //channel.BasicConsume("hello", true, consumer);
                    //Console.WriteLine(" waiting for message.");
                    //while (true)
                    //{
                    //    var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
                    //    var body = ea.Body;
                    //    var message = Encoding.UTF8.GetString(body);
                    //    Console.WriteLine("Received {0}", message);

                    //}
                    

                    channel.BasicQos(0, 1, false);

                    var consumer2 = new EventingBasicConsumer(channel);

                    channel.BasicConsume(queue: "task_queue", autoAck: true, consumer: consumer2);

                    consumer2.Received += (modal, ea) =>
                      {
                          var body = ea.Body;
                          var message = Encoding.UTF8.GetString(body);
                          #region MyRegion
                          //用点来表示执行时长
                          int dots = message.Split('.').Length - 1;
                          Thread.Sleep(dots * 1000);
                          #endregion
                          Console.WriteLine("Received {0}", message);
                          Console.WriteLine("Done");

                          channel.BasicAck(ea.DeliveryTag, false);
                      };
                    


                }
            }
        }
    }
}
